<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <a-card :bordered="false">
      <h3>{{id == 'null' ? '新增' : '编辑'}}任务</h3>
      <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 6 }, sm: { span: 8 } }" :wrapperCol="{ lg: { span: 14 }, sm: { span: 16 } }">
        <h4>确认任务对象和类型</h4>
        <a-form-model-item label="任务对象" prop="taskObject">
          <a-select v-model="form.taskObject" @change="taskObjectChange" placeholder="请选择" show-search :filter-option="filterOption">
            <a-select-option :value="3">导购</a-select-option>
            <a-select-option :value="2">用户</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="任务类型" prop="taskType">
          <a-select v-model="form.taskType" placeholder="请选择" show-search :filter-option="filterOption">
            <a-select-option :value="1" :disabled="!(form.taskObject ==3)">拉新任务</a-select-option>
            <a-select-option :value="2" :disabled="!(form.taskObject ==3)">发帖任务</a-select-option>
            <a-select-option :value="3" :disabled="!(form.taskObject ==2)">首帖奖励</a-select-option>
          </a-select>
        </a-form-model-item>
        <h4>填写任务信息</h4>
        <template v-if="form.taskObject == 3">
          <a-form-model-item label="任务名称" prop="taskName">
            <a-input v-model.trim="form.taskName" placeholder="" allowClear :maxLength="24" />
            <div>限24个字符以内</div>
          </a-form-model-item>
          <a-form-model-item label="任务说明（选填）">
            <a-input v-model.trim="form.taskRemark" placeholder="限24个字符以内" :maxLength="24" allowClear />
          </a-form-model-item>
          <a-form-model-item label="任务开始时间-任务结束时间" prop="time">
            <a-range-picker style="width:100%;" show-time valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" v-model="form.time" />
          </a-form-model-item>
          <a-form-model-item label="奖励信息" prop="awardInfo">
            <a-textarea v-model.trim="form.awardInfo" placeholder="限50个字符以内" :maxLength="50" :rows="3" allowClear />
          </a-form-model-item>
          <a-form-model-item label="任务目标" prop="taskTarget">
            <a-input-number v-model="form.taskTarget" :min="1" :max="999" />
          </a-form-model-item>
        </template>
        <template v-if="form.taskObject == 2">
          <a-form-model-item label="关联优惠券" required>
            <a-table bordered :pagination="false" :columns="columns" :data-source="form.discountCoupon" :rowKey="(record, index) => index">
              <span slot="coupon" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`discountCoupon.${index}.coupon`" :rules="{ required: true, message: '请输入券ID', trigger: 'blur' }">
                  <a-input v-model.trim="record.coupon" placeholder="请输入券ID" allowClear  />
                </a-form-model-item>
              </span>
              <span slot="num" slot-scope="text, record, index">
                <a-form-model-item label="" :prop="`discountCoupon.${index}.num`" :rules="{ required: true, message: '请输入', trigger: 'blur' }">
                  <a-input-number v-model="record.num" :min="1" />
                </a-form-model-item>
              </span>
              <span slot="action" slot-scope="text, record, index">
                <a-icon type="delete" @click="handleRemove(index)" />
              </span>
            </a-table>
            <a @click="handleAdd">关联新的优惠券</a>
          </a-form-model-item>
        </template>
        <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
          <a-button style="margin-right: 8px" @click="handleBack">取消</a-button>
          <a-button htmlType="submit" @click="handleSubmit" type="primary">保存</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-card>
  </a-spin>
</template>
<script>
import { taskManagerAdd, taskDetail, taskManagerEdit } from '@/api/micromall/communityMarketing'

const columns = [
  {
    title: '优惠券',
    width: '100px',
    align: 'center',
    scopedSlots: { customRender: 'coupon' }
  },
  {
    title: '张数',
    width: '50px',
    align: 'center',
    scopedSlots: { customRender: 'num' }
  },
  {
    title: '操作',
    width: '50px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
  },
  data() {
    return {
      id: this.$route.params.id,
      spinning: false,
      columns,
      form: {
         time: [],
        taskType: '',
        discountCoupon: [
          {
            coupon: '',
            num: ''
          }
        ]
      },
      rules: {
        taskName: [{ required: true, message: '请输入', trigger: 'blur' }], 
        taskObject: [{ required: true, message: '请选择', trigger: 'change' }],
        taskType: [{ required: true, message: '请选择', trigger: 'change' }],
        time: [{ required: true, message: '请选择', trigger: 'change' }],
        awardInfo: [{ required: true, message: '请输入', trigger: 'blur' }],
        taskTarget: [{ required: true, message: '请输入', trigger: 'blur' }],
        adType: [{ required: true, message: '请选择', trigger: 'change' }],
        jumpType: [{ required: true, message: '请选择', trigger: 'change' }],
        contentType: [{ required: true, message: '请选择', trigger: 'change' }],
        content: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        releaseTime: [{ required: true, message: '请选择', trigger: 'change' }],
        approvalStatus: [{ required: true, message: '请选择', trigger: 'change' }],
        buyerShowGroups: [{ required: true, message: '请选择', trigger: 'change' }]
      }
    }
  },
  watch: {
  },
  created() {
    this.getDetails()
  },
  computed: {},
  mounted() {},
  beforeDestroy() {},
  methods: {
    taskObjectChange() {
      this.form.taskType = ''
    },

    // 获取详情
    getDetails() {
      if (this.id == 'null') return
      const data = {
        id: this.id
      }
      taskDetail(data)
        .then(res => {
          if (res.code === 200) {
            const { discountCoupon, startTime, endTime } = res.data 
            const discountCouponObj = discountCoupon ? JSON.parse(discountCoupon) : {}
            const discountCouponArr = []
            Object.keys(discountCouponObj).forEach(i => {
              discountCouponArr.push({
                coupon: i,
                num: discountCouponObj[i]
              })
            })
             console.log(discountCouponArr, 'this.form')
            this.form = {
              ...res.data,
              discountCoupon: discountCouponArr,
              time: startTime && endTime ? [startTime, endTime] : []
            }
           
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
        .catch(err => {})
    },

    // 关联新的优惠券
    handleAdd() {
      this.form.discountCoupon.push({
        coupon: '',
        num: ''
      })
    },

    // 移除关联
    handleRemove(index) {
      if (this.form.discountCoupon.length < 2) {
        this.$message.error('不能再删了！')
        return
      }
      this.form.discountCoupon.splice(index, 1)
    },

    // 确认
    handleSubmit() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          const taskManagerAddOrEdit = this.id == 'null' ? taskManagerAdd : taskManagerEdit
          const { time, discountCoupon, taskObject } = this.form
          const discountCouponObj = {}
          discountCoupon.forEach(e => {
            discountCouponObj[e.coupon] = e.num + ''
          })
          const data = {
            ...this.form,
            discountCoupon: taskObject == 2 && discountCoupon.length ? JSON.stringify(discountCouponObj) : '',
            startTime: time.length ? time[0] : null,
            endTime: time.length ? time[1] : null
          }
          this.spinning = true
          taskManagerAddOrEdit(data).then(res => {
            if (res.code === 200) {
              this.$router.go(-1)
            } else {
              this.spinning = false
              this.$message.error(res.msg || res.message)
            }
          }).catch(err => {
            this.spinning = false
          })
          
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    //返回
    handleBack() {
      this.$router.go(-1)
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  }
}
</script>
<style lang="less" scoped>
.hidden-title /deep/ .ant-form-item-label > label {
  visibility: hidden;
}
</style>
